//
//  BGShopAddListCell.m
//  bigMall
//
//  Created by LTOVE on 16/8/9.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGShopAddListCell.h"
#import "BGShopAddListBasicModel.h"

#import "BGAddListTitleModel.h"
#import "BGAddListTextFildViewModel.h"
#import "BGAddlistWithaccessoryViewModel.h"

static NSString *const reuserIdentify = @"cell";
//static NSString *const reuserIdentify = @"cell";

@interface BGShopAddListCell ()<PickViewChangedDelegate>{

    NSString *_textFildStr;
    UITextField *_textFild;
    NSMutableArray *_chooseArray;
    NSMutableArray *_valueArray;
    NSString *_idStr;
    NSIndexPath *_indexPath;
}

@end

@implementation BGShopAddListCell



- (void)setModel:(BGShopAddListBasicModel *)model
{
    _model = model;
    //初始化cell视图
    [self setUpSubviewsWithModel:model];
}

- (void)setUpSubviewsWithModel:(BGShopAddListBasicModel *)model
{
    
    if ([model isKindOfClass:[BGAddListTitleModel class]]) {
        //title
        BGAddListTitleModel *itemModel = (BGAddListTitleModel *)model;
     [self lableWithString:itemModel.title];
        
        
    }else if ([model isKindOfClass:[BGAddListTextFildViewModel class]]){
    //textFild
        BGAddListTextFildViewModel *itemModel = (BGAddListTextFildViewModel *)model;
        [self textFildCellWithTitle:itemModel.title textFild:itemModel.textFildStr];
        
    }else if ([model isKindOfClass:[BGAddlistWithaccessoryViewModel class]]){
    //pickView
        BGAddlistWithaccessoryViewModel *itemModel = (BGAddlistWithaccessoryViewModel *)model;
        itemModel.delegate = self;
        [self pickViewCellWithtitle:itemModel.title];
    }else if ([model isKindOfClass:[BGShopAddListBasicModelType4 class]]){
//        self.textLabel.text = @"s";
        [self addDoubleChoseViewWithModel:(BGShopAddListBasicModelType4 *)model];
    }
    
    
    
}

- (void)addDoubleChoseViewWithModel:(BGShopAddListBasicModelType4 *)model
{
    [self cleanContentView];
//    NSArray *array = model.is_default;
    _chooseArray = [[NSMutableArray alloc]initWithArray:model.is_default];
    _valueArray = [[NSMutableArray alloc]initWithArray:model.dataArray];
    _idStr = model.idStr;
    _indexPath = model.indexPath;
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = model.title;
    titleLabel.font = Font34;
    titleLabel.textColor = textBlackColor;
    [titleLabel sizeToFit];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:titleLabel];
    NSDictionary *viewDic = NSDictionaryOfVariableBindings(titleLabel);
    [viewDic setValue:self.contentView forKey:@"superView"];
    //水平约束
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-20-[titleLabel]-20-|" options:0 metrics:nil views:viewDic]];
    //顶部约束
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:5]];
    //添加按钮
    for (int i = 0 ; i < model.dataArray.count; i++) {
        UIView *view = [self addListViewWithDataArray:model.dataArray[i] andDefaultArray:model.is_default[i] tag:i];
        [viewDic setValue:view forKey:[NSString stringWithFormat:@"view%d",i]];
        //约束
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"|-20-[view%d]-20-|",i] options:0 metrics:nil views:viewDic]];
    }
    for (int i = 0 ; i < model.dataArray.count; i++) {
        if (i == 0) {
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[titleLabel]-5-[view0]" options:0 metrics:nil views:viewDic]];
        }else{
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view%d]-5-[view%d]" ,i - 1,i]options:0 metrics:nil views:viewDic]];
        }
        if (i == model.dataArray.count - 1) {
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view%d]-5-|",i] options:0 metrics:nil views:viewDic]];
            NSLog(@"1111");
        }
    }
    
}

- (UIView *)addListViewWithDataArray:(NSString *)dataArray andDefaultArray:(NSString *)defaultArray tag:(NSUInteger)tag
{
    UIView *view = [UIView new];
    
    view.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"pay_unselect"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"pay_selected"] forState:UIControlStateSelected];
    [btn setImage:[UIImage imageNamed:@"pay_unselect"] forState:UIControlStateHighlighted];
    btn.selected = [defaultArray isEqualToString:@"true"] ? YES : NO;
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.tag = tag;
    [btn addTarget:self action:@selector(doubleBtnCilck:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    UILabel *label = [UILabel new];
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.text = dataArray;
    label.font = Font30;
    [label sizeToFit];
    [view addSubview:label];
    //添加约束
    [view addConstraint:[NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:btn attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:BGMaginLeft]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:btn attribute:NSLayoutAttributeRight multiplier:1.0 constant:5]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    [self.contentView addSubview:view];
    return view;
}

- (void)doubleBtnCilck:(UIButton *)btn
{
    btn.selected = !btn.selected;
    _chooseArray[btn.tag] = btn.selected ? @"true" : @"false";
    NSArray *aaaa = [self getChangedValue];
//    NSLog(@"%@",aaaa);
    if ([_delegate respondsToSelector:@selector(cellValueWithDoubleValueChangedWithArray: adnIndexPath:)]) {
        [_delegate cellValueWithDoubleValueChangedWithArray:aaaa adnIndexPath:_idStr];
    }
}

- (NSArray *)getChangedValue
{
    NSMutableArray *array = [NSMutableArray array];
    for (int i =0 ; i < _chooseArray.count; i++) {
        if ([_chooseArray[i] isEqualToString:@"true"]) {
            NSString *str = _valueArray[i];
            str = [[str componentsSeparatedByString:@"浮"] firstObject];
            NSDictionary *dic = @{
                                    @"id":_idStr,
                                    @"value":str
                                  };
            [array addObject:dic];
        }
    }
    return array;
}

/**
 *  pickView的视图
 *
 *  @param title title description
 */
- (void)pickViewCellWithtitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc]init];
    label.text = title;
    label.font = Font30;
    label.textColor = textBlackColor;
    [label sizeToFit];
    label.x = BGMaginLeft;
    label.centerY = self.height * 0.5;
    [self cleanContentView];
    [self.contentView addSubview:label];
//    self.textLabel.text = title;
//    self.textLabel.font = Font30;
//    self.textLabel.textColor = textBlackColor;
    self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
}



/**
 *  创建textfild视图
 *
 *  @param title       title description
 *  @param textFildstr textFildstr description
 */
- (void)textFildCellWithTitle:(NSString *)title textFild:(NSString *)textFildstr
{
    [self cleanContentView];
    //创建label
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = title;
    titleLabel.font = Font30;
    titleLabel.textColor = textBlackColor;
    [titleLabel sizeToFit];
    titleLabel.x = BGMaginLeft;
    titleLabel.centerY = self.height * 0.5;
//    NSLog(@"%f",titleLabel.centerY);
    
    [self.contentView addSubview:titleLabel];
    //创建textfile
    UITextField *textFildView = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame) + 5, self.height * 0.5, self.width - CGRectGetMaxX(titleLabel.frame), self.height)];
    textFildView.centerY = self.height * 0.5;
    
    textFildView.placeholder = textFildstr;
//    textFildView.text = textFildstr;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanTextfildText) name:@"textFildChange" object:nil];
    _textFildStr = textFildstr;
    _textFild = textFildView;
    textFildView.textColor = textGrayColor;
    textFildView.font = Font30;
    textFildView.keyboardType = UIKeyboardTypeDecimalPad;
    [textFildView addTarget:self action:@selector(textFildChangedWith:) forControlEvents:UIControlEventEditingChanged];
//    self.contentView removes
    [self.contentView addSubview:textFildView];
}

- (void)cleanTextfildText
{
    _textFild.text = nil;
}

/**
 *  textFild值改变的通知
 *
 *  @param textFildView textFildView description
 */
- (void)textFildChangedWith:(UITextField *)textFildView
{
#warning 此处应该有代理方法
    CGFloat maxValue = [_textFildStr floatValue];
//    GWLog(@"%@",textFildView.text);
    [self statementDelegateWithString:textFildView.text isTextFild:YES];
    
    
    BGAddListTextFildViewModel *itemModel = (BGAddListTextFildViewModel *)self.model;
    itemModel.textFildStr = textFildView.text;
    
    if ([_delegate respondsToSelector:@selector(cellValueChangedWithModel:)]) {
        [_delegate cellValueChangedWithModel:itemModel];
    }
    
}


#pragma pickView值改变的代理方法

- (void)pickViewValueChanged:(NSString *)ChangedValue
{
//    GWLog(@"cell -%@",ChangedValue);
    BGAddlistWithaccessoryViewModel *itemModel = (BGAddlistWithaccessoryViewModel *)self.model;
    itemModel.textStr = ChangedValue;
    
//    if ([_delegate respondsToSelector:@selector(cellValueChangedWithModel:)]) {
//        [_delegate cellValueChangedWithModel:itemModel];
//    }
//    
    [self statementDelegateWithString:ChangedValue isTextFild:NO];
}

- (void)statementDelegateWithString:(NSString *)str isTextFild:(BOOL)isTextFild
{
    if ([_delegate respondsToSelector:@selector(cellValueChanged:istextFild:)]) {
        [_delegate cellValueChanged:str istextFild:isTextFild];
    }
}

- (void)cleanContentView
{
    for (UILabel *label in self.contentView.subviews) {
        [label removeFromSuperview];
    }
}

/**
 *  titleLabel富文本
 *
 *  @param strings strings description
 *
 *  @return return value description
 */
- (void)lableWithString:(NSString *)strings
{
    [self cleanContentView];
    UILabel *label = [[UILabel alloc]init];
    NSRange rang = [strings rangeOfString:@":"];
    
    NSDictionary *dic = @{
                          NSFontAttributeName:Font30,
                          NSForegroundColorAttributeName:textBlackColor
                          };
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:strings attributes:dic];
    
    NSDictionary *resetDict = @{
                                NSFontAttributeName:Font22,
                                NSForegroundColorAttributeName:read_
                                };
    if (!(rang.location == NSNotFound)) {
       [attrStr addAttributes:resetDict range:NSMakeRange(rang.location + 1, strings.length - rang.location -1)];
        
    }
    label.attributedText = attrStr;
    [label sizeToFit];
    
    label.x = BGMaginLeft;
    label.centerY = self.height * 0.5;
    [self.contentView addSubview:label];
//    return label;
}


+ (BGShopAddListCell *)cellWithTableView:(UITableView *)tableView IndexPath:(NSIndexPath *)indexPath
{
//    NSString *ID = @"cell";
    BGShopAddListCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentify];
    
    if (!cell) {
      
        cell = [[self alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuserIdentify];
    }
    return cell;
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    // Configure the view for the selected state
}
@end
